package ar.com.binarit

import grails.validation.ValidationException
import ar.com.binarit.entities.Categoria

class NuevaMubbiaController extends AbstractMubbiaController {
	
    def index() { 
		
		if (!springSecurityService.isLoggedIn()){
			render(view: "/login/mustLogin")
		}
		
		def mubbiaInstance = llenarDatosMubbia(params, true)
		if (!mubbiaInstance.puedeEditarMubbia(springSecurityService.currentUser)){
			redirect(action: "show", params: params)
		}
		def result = [mubbiaInstance: mubbiaInstance]
		result.putAll(getMapaDatos(mubbiaInstance))
		result
	}
	
	def show() {
		log.warn "show: ${params}"
		redirect(controller:"mubbias", action: "show", params:params)	
	}
	
	def editarMubbia = {
		def result
		def mubbiaInstance
		try{
			mubbiaInstance = llenarDatosMubbia(params, true)
			result = mubbiaService.validarMubbia(mubbiaInstance)
			if (result){
				mubbiaService.guardarMubbia(mubbiaInstance)
			}
		}catch (ValidationException e) {
			result = false
		}
		mostrarResultados(result, "Mubbia correcta", mubbiaInstance)
	}  
	
	def previsualizarMubbia = {
		def result
		def mubbiaInstance
		try{
			mubbiaInstance = llenarDatosMubbia(params, true)
			result = mubbiaService.validarMubbia(mubbiaInstance)
			if (result){
				mubbiaService.guardarMubbia(mubbiaInstance)
			}
		}catch (ValidationException e) {
			result = false
		}
		mostrarResultados(result, "Mubbia correcta", mubbiaInstance)
	}
	
	def unirseAMubbia = {
		def result = true
		try{
			def mubbiaInstance = mubbiaService.obtenerMubbia(params.mubbiaId)
			if (mubbiaInstance){
				def Person = Person.findById(springSecurityService.currentUser?.id)
				mubbiaService.unirseAMubbia(mubbiaInstance, Person)
			}
		}catch (ValidationException e) {
			result = false
		}
		redirect(action: "show", params:[mubbiaId:params?.mubbiaId])
	}
	
	def desunirseAMubbia = {
		def result = true
		try{
			def mubbiaInstance = mubbiaService.obtenerMubbia(params.mubbiaId)
			if (mubbiaInstance){
				def Person = Person.findById(springSecurityService.currentUser?.id)
				mubbiaService.desunirseAMubbia(mubbiaInstance, Person)
			}
		}catch (ValidationException e) {
			result = false
		}
		redirect(action: "show", params:[mubbiaId:params?.mubbiaId])
	}
	
	def publicarMubbia = {
		def result = true
		try{
			def mubbiaInstance = mubbiaService.obtenerMubbia(params.mubbiaId)
			if (mubbiaInstance){
				mubbiaService.publicarMubbia(mubbiaInstance)
			}
		}catch (ValidationException e) {
			result = false
		}
		redirect(action: "show", params:[mubbiaId:params?.mubbiaId])
	}
	
//	def dibujarUbicaciones = {
//		println "paso por dibujar"
//		render(template: "/templates/seleccionarUbicacion")
//	}
	
	def getMapaDatos(mubbiaInstance){
		[categorias:Categoria.all.sort{it.descripcion},
		tags : mubbiaInstance?.tags?.toString().replace('[', '').replace(']', '')] + super.getMapaDatos(mubbiaInstance)
	}
	
}
